<template>
  <div class="stock">
    <van-cell is-link icon="/imgs/stock_icon.png">
      <template #title>
        <h5>股票榜单</h5>
      </template>
    </van-cell>
    <!-- 股票榜单 -->
    <van-tabs v-model="active">
      <van-tab v-for="(item, i) in stocks" :key="i" :title="markets[i]">
        <van-cell-group inset>
          <van-cell
            ><template>
              <div
                class="inset-cell"
                v-for="(stock, index) in item"
                :key="stock.value"
              >
                <span class="num">{{ index + 1 }}</span>
                <span class="name">{{ stock.name }}</span>
                <span class="arrow" :class="stock.percent > 0 ? 'up' : 'down'"
                  ><van-icon name="down"
                /></span>
                <span class="value">{{ stock.value }}</span>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import * as api from "@/api/index";
export default {
  data() {
    return {
      active: 0,
      markets: ["全球", "沪深", "港股", "美股"],
      stocks: [],
    };
  },
  mounted() {
    let num = 0;
    this.markets.forEach(async (item, i) => {
      let res = await api.getStocks({ type: i });
      //   this.stocks.push(res.data.items);  // 无法确认返回时的顺序
      this.stocks[i] = res.data.items; // vue不会监听到这样的数组改变
      num++;
      if (num === 4) {
        // this.stocks = [...this.stocks]; // 重新解构赋值让vue能够监听到
        // 或者使用强制更新
        // this.$forceUpdate();
        // 或者使用$set 更新
        this.$set(this.stocks);
        // console.log(this.stocks);s
      }
    });
  },
};
</script>

<style lang="less" scoped>
.stock {
  h5 {
    margin: 0;
    font-size: 0.4rem;
    color: #666;
    text-align: left;
    padding-left: 0.1rem;
  }
  .van-icon img {
    width: 0.6rem;
    height: 0.6rem;
  }
  .arrow.up {
    color: orangered;
    i {
      transform: rotate(180deg);
    }
  }
  .arrow.down {
    color: green;
  }
  .inset-cell {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 1.2rem;
    .num {
      flex: 1;
    }
    .name {
      flex: 7;
    }
    .arrow {
      flex: 1;
    }
    .value {
      flex: 2;
      display: flex;
      justify-content: center;
    }
  }
  /deep/ .van-tabs__line {
    background-color: #1989fa;
  }
}
</style>
